<?php

namespace app\admin\controller\health\tracking;

use app\common\controller\Backend;
use app\health\model\tracking\HealthTrackingUrlCode;

class Url extends Backend
{
    protected $code = [
        'sms_template_x' => [
            'code'  => 'sms_template_x',
            'title' => '短信模板X'
        ],
        'sms_template_y' => [
            'code'  => 'sms_template_y',
            'title' => '短信模板Y'
        ]
    ];

    public function _initialize()
    {
        parent::_initialize();
        sort($this->code);
        $this->assignconfig([
            'code_map' => $this->code
        ]);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $code    = $this->request->param('code');
            $summary = HealthTrackingUrlCode::where('code', $code)->field('sum(put_in) as put_in_count,sum(click_num) as click_num_count')->find()->toArray();
            $summary = array_filter($summary);
            if (!$summary) {
                $summary = ['put_in_count' => 0, 'click_num_count' => 0, 'rate' => 0];
            } else {
                $summary['rate'] = bcmul(bcdiv($summary['click_num_count'], $summary['put_in_count'], 4), 100, 2);
            }
            $this->success('', '', compact('summary'));
        }
        return $this->view->fetch();
    }

    public function lists()
    {
        if ($this->request->isAjax()) {
            $code     = $this->request->param('code');
            $paginate = HealthTrackingUrlCode::where('code', $code)
                ->order('day', 'desc')
                ->paginate($this->request->param('limit/d', 10))
                ->each(function ($item) {
                    $item->rate = bcmul(bcdiv($item['click_num'], $item['put_in'] > 0 ? $item['put_in'] : $item['click_num'], 4), 100, 2) . '%';
                });
            $this->success('', '', $paginate);
        }
    }
}
